
var fs = require("fs");
var newsModel = require("../models/news.model");
var commentModel = require("../models/comment.model");

module.exports={
    getIndexData:function(req, res, next){
        //1升序，-1降序
        newsModel.find({"deleted": false}).sort({'type': 1, "top" : -1, "date": -1}).exec(function(err,data){
            if(err){
                console.error(err);
                res.json({
                    success:false,
                    description:"获取数据失败",
                    data:{}
                });
            }else{
                let result = [], 
                    typeObj = { //一种类别的数据
                        type: data[0].type, 
                        data:[] 
                    }, 
                    li = 0, //记录现在这个类别的数据有几条
                    limit = 12;//总共需要的数据条数
                
                for(let i = 0; i < data.length; i++){
                    if(data[i].type === typeObj.type){
                        if(li >= limit) continue; 
                        else{
                            typeObj.data.push(data[i]);
                            li++;
                        }
                    }else{
                        result.push(typeObj);
                        typeObj = { type: data[i].type, data :[] };
                        li = 0;
                        type = data[i].type;
                    }
                }
                result.push(typeObj);

                res.json({
                    success: true,
                    description: "每个类别的12条数据",
                    data: result
                })
            }
        })
    },
    getArticleDetail:function(req, res, next){
        if(req.query.id){
            newsModel.find({_id:req.query.id}, function(err, data){
                if(err){
                    console.error(err);
                    res.json({
                        success:false,
                        description:"数据库查询出错",
                        data:{}
                    })
                }else{
                    data = data[0];
                    fs.readFile(data.content , function(err, nowdata) {
                        if(err){
                            console.error("读取文件失败");
                            res.json({
                                success:false,
                                description:'获取文章的内容失败',
                                data: {}
                            })
                        }else{
                            data.content = nowdata;
                            let like = false;
                            if(data.people){
                                if(req.query.username){
                                    //用户登录了，检查用户是否点赞过这篇文章
                                    if(data.people.indexOf(req.query.username) !== -1)like = true;
                                }
                                delete data.people;//点赞过的人就不用传过去了，浪费带宽
                            }
                            res.json({
                                success:true,
                                data: {
                                    data:data,
                                    like:like
                                }
                            })
                        }
                    });
                }
            })
        }else{
            res.json({
                success:false,
                description:"没有传id过来，无法获取文章详情",
                data:{}
            })
        }
    },
    articleDislike:function(req, res, next){
        let body = JSON.parse(req.body.data);
        console.log("取消喜欢", body);
        if(body.id && body.username){
            newsModel.find({_id:body.id}, function(err, data){
                if(err){
                    console.error(err);
                    res.json({
                        success:false,
                        description:"查询取消喜欢的文字失败",
                        data:{}
                    })
                }else{
                    if(data){
                        data = data[0];
                        if(data.people){
                            let newpeople = data.people;
                            let index = newpeople.indexOf(body.username);
                            if(index !== -1){
                                newpeople.splice(index, 1);
                            }
                            newsModel.findByIdAndUpdate(body.id,{people: newpeople, like: data.like - 1}, function(err, data){
                                if(err){
                                    console.error(err);
                                    res.json({
                                        success: false,
                                        description: "取消点赞更新的时候失败",
                                        data: {}
                                    })
                                }else{
                                    res.json({
                                        success:true,
                                        data:{}
                                    })
                                }
                            });
                        }else{
                            res.json({
                                success:false,
                                description:"该用户还没有点赞不能取消",
                                data:{}
                            })
                        }
                    }else{
                        res.json({
                            success:false,
                            description:"取消喜欢没有数据",
                            data:{}
                        })
                    }
                }
            })
        }
    },
    articleLike:function(req, res, next){
        let body = JSON.parse(req.body.data);
        if(body.id && body.username){
            newsModel.find({_id:body.id}, function(err, data){
                if(err){
                    console.error(err);
                    res.json({
                        success:false,
                        description:"点赞的查询出错",
                        data:{}
                    })
                }else{
                    if(data){
                        data = data[0];
                        let newpeople = data.people || [];
                        newpeople.push(body.username);
                        newsModel.findByIdAndUpdate(body.id, { people: newpeople,like: data.like + 1 }, function(err, data){
                            if(err){
                                console.error(err);
                                res.json({
                                    success: false,
                                    description:"点赞插入的时候出错",
                                    data:err
                                })
                            }else{
                                console.log("点赞完成",data);
                                res.json({
                                    success:true,
                                    data:data
                                })
                            }
                        })
                    }else{
                        res.json({
                            success:false,
                            description:"点赞的查询不到这篇文章",
                            data:{}
                        })
                    }
                }
            })
        }else{
            req.json({
                success:false,
                description:"没有id或者用户名",
                data:{}
            })
        }
    },
    getOneTypeArticles:function(req, res, next){
        //获取某个类型的所有文章，按照分页查询
        let filter = { deleted: false, type: Number(req.query.type) };
        if(req.query.searchContent){
            filter.title = {$regex : new RegExp(req.query.searchContent), $options:"$i"};
        }
        let total = 0;//总共有多少条数据
        newsModel.find(filter).exec((err, data)=>{
            if(err){
                console.error(err);
            }else{
                total = data.length;
            }
        })
        newsModel.find(filter).skip(Number(req.query.pageSize) * Number(req.query.page - 1)).limit(Number(req.query.pageSize)).sort({"top" : -1, "date": -1}).exec(function(err, data){
            if(err){
                console.error(err);
                res.json({
                    success:false,
                    description:req.query.type+"类型文章查询出错",
                    data:{}
                });
            }else{
                res.json({
                    success:true,
                    data:{
                        page:req.query.page,
                        data:data,
                        total:total
                    }
                })
            }
        });
    },
    getComments:function(req, res, next){
        let sort = 0, sortObj = {}, total = 0, filter={deleted: false};

        //sort为0按照时间排序，为1按照点赞排序
        if(Number(req.query.sort) === 1)sort = 1;
        if(sort){
            sortObj.like = -1;
            sortObj.date = -1;
        }else{
            sortObj.date = -1;
        }
        commentModel.find(filter,(err, data)=>{
            if(err){
                console.error(err)
            }else{
                total = data.length;
            }
        })
        commentModel.find(filter).skip(Number(req.query.pageSize) * Number(req.query.page - 1)).limit(Number(req.query.pageSize)).sort(sortObj).exec((err, data)=>{
            if(err){
                console.error(err)
                res.json({
                    success:false,
                    description:"查询评论出错"
                })
            }else{
                let like = [], nowdata = data;
                //添加用户是否点赞过
                if(req.query.username){
                    for(let i = 0; i < nowdata.length; i++){
                        nowdata[i].people.indexOf(req.query.username) !== -1?
                        like.push(true):
                        like.push(false);
                        delete nowdata[i].people;
                    }
                }else{
                    for(let i = 0; i < data.length; i++) {
                        like.push(false);
                        delete nowdata[i].people;
                    }
                }
                console.log("评论返回条数", data.length, "limit:",req.query);
                // console.log("data", data);
                // console.log(nowdata);
                res.json({
                    success: true,
                    data:{
                        total: total,
                        data: nowdata,
                        like: like
                    }
                })
            }
        })
    },
    addComment:function(req, res, nex){
        let body = JSON.parse(req.body.data);
        if(body.username && body.comment){
            let comment = new commentModel({
                username: body.username,
                comment: body.comment,
                date: Date.now()
            })
            comment.save((err, data)=>{
                if(err){
                    console.error(err);
                    res.json({
                        success: false,
                        description:"插入评论失败"
                    })
                }else{
                    res.json({
                        success: true,
                        data:data
                    })
                }
            })
        }
    },
    commentDislike:function(req, res, next){
        let body = JSON.parse(req.body.data);
        console.log("取消喜欢", body);
        if(body.id && body.username){
            commentModel.find({_id:body.id}, function(err, data){
                if(err){
                    console.error(err);
                    res.json({
                        success:false,
                        description:"查询取消喜欢的文字失败",
                        data:{}
                    })
                }else{
                    if(data){
                        data = data[0];
                        if(data.people){
                            let newpeople = data.people;
                            let index = newpeople.indexOf(body.username);
                            if(index !== -1){
                                newpeople.splice(index, 1);
                            }
                            commentModel.findByIdAndUpdate(body.id,{people: newpeople, like: data.like - 1}, function(err, data){
                                if(err){
                                    console.error(err);
                                    res.json({
                                        success: false,
                                        description: "取消点赞更新的时候失败",
                                        data: {}
                                    })
                                }else{
                                    res.json({
                                        success:true,
                                        data:{}
                                    })
                                }
                            });
                        }else{
                            res.json({
                                success:false,
                                description:"该用户还没有点赞不能取消",
                                data:{}
                            })
                        }
                    }else{
                        res.json({
                            success:false,
                            description:"取消喜欢没有数据",
                            data:{}
                        })
                    }
                }
            })
        }
    },
    commentLike:function(req, res, next){
        let body = JSON.parse(req.body.data);
        if(body.id && body.username){
            commentModel.find({_id:body.id}, function(err, data){
                if(err){
                    console.error(err);
                    res.json({
                        success:false,
                        description:"点赞的查询出错",
                        data:{}
                    })
                }else{
                    if(data){
                        data = data[0];
                        let newpeople = data.people || [];
                        newpeople.push(body.username);
                        commentModel.findByIdAndUpdate(body.id, { people: newpeople, like: data.like + 1 }, function(err, data){
                            if(err){
                                console.error(err);
                                res.json({
                                    success: false,
                                    description:"点赞插入的时候出错",
                                    data:err
                                })
                            }else{
                                console.log("点赞完成",data);
                                res.json({
                                    success:true,
                                    data:data
                                })
                            }
                        })
                    }else{
                        res.json({
                            success:false,
                            description:"点赞的查询不到这篇文章",
                            data:{}
                        })
                    }
                }
            })
        }else{
            req.json({
                success:false,
                description:"没有id或者用户名",
                data:{}
            })
        }
    }
}